// import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import { getAccessToken } from '@/utils/auth'
// import { isFileStream } from '@/utils'
import router from '../router'

export function handleHttpErrorCode(res) {
  if (res.status === 401) {
    MessageBox.confirm('系统登录已过期，可以取消以停留在此页面或重新登录 ', 'Confirm logout', {
      confirmButtonText: '重新登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    })
  } else if (res.status === 402 || res.status === 403) {
    MessageBox.confirm(
      '您可能没有该功能或资源的操作权限，请与管理员联系以查明您是否有访问权限。',
      '访问受限',
      {
        confirmButtonText: '确定',
        type: 'warning',
        iconClass: 'em-icon-authority',
        showCancelButton: false,
        closeOnClickModal: false,
        showClose: false,
        center: true
      }
    )
      .then(() => {
        console.log('qued')
        router.go(-1)
      })
      .catch(() => {
        router.go(-1)
      })
  } else if (res.status === 429) {
    Message({
      message: res.message || 'Error',
      type: 'error',
      duration: 5 * 1000
    })
  } else {
    Message({
      message: res.message || 'Error',
      type: 'error',
      duration: 5 * 1000
    })
  }

  console.log('_Axios Response Error:', res) // for debug
  return Promise.reject(new Error(res.message || 'Error'))
}
// response interceptor
/**
 * Response interceptor
 *
 * If you want to get http information such as headers or status
 * Please return  response => response
 *
 * Determine the request status by custom code
 * Here is just an example
 * You can also judge the status by HTTP Status Code
 */
export default function handleHttpExceptions(error) {
  // console.log('_Axios Response Error:', error) // for debug
  // console.log(error) // for debug
  // console.log(error.code, error.name, error.message, error.response)
  if (typeof error === 'object' && error && error.response) {
    console.log(error.response.headers)
    if (
      error.response.request.responseType &&
      error.response.headers['content-type'].indexOf('application/json') !== -1
    ) {
      var blob = new Blob([error.response.data])
      const reader = new FileReader()
      reader.readAsText(blob)
      var parseObj = {}
      reader.onload = e => {
        const readerres = reader.result
        parseObj = JSON.parse(readerres)
        return handleHttpErrorCode(parseObj)
      }
      return Promise.reject(error)
    } else {
      return handleHttpErrorCode(error.response)
    }
  } else {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
  // Message({
  //   message: error.message,
  //   type: 'error',
  //   duration: 5 * 1000
  // })
  // return Promise.reject(error)
}
